import 'dart:async';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('圆形图片示例')),
        body: Center(
          child: SizedBox(
            width: 200,
            height: 200,
            child: LocalImagePainter(
              imageAsset: 'assets/demo.jpg',
              borderWidth: 3,
              borderColor: Colors.blue,
            ),
          ),
        ),
      ),
    );
  }
}

class LocalImagePainter extends StatefulWidget {
  final String imageAsset;
  final double borderWidth;
  final Color borderColor;

  const LocalImagePainter({
    required this.imageAsset,
    this.borderWidth = 2,
    this.borderColor = Colors.white,
  });

  @override
  _LocalImagePainterState createState() => _LocalImagePainterState();
}

class _LocalImagePainterState extends State<LocalImagePainter> {
  late Future<ui.Image> _imageLoader;

  @override
  void initState() {
    super.initState();
    _imageLoader = _loadImage(widget.imageAsset);
  }

  Future<ui.Image> _loadImage(String assetPath) async {
    final byteData = await rootBundle.load(assetPath);
    final bytes = byteData.buffer.asUint8List();
    final codec = await ui.instantiateImageCodec(bytes);
    final frame = await codec.getNextFrame();
    return frame.image;
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<ui.Image>(
      future: _imageLoader,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          if (snapshot.hasError) {
            return Icon(Icons.error, color: Colors.red);
          }
          return CustomPaint(
            painter: CircleImagePainter(
              image: snapshot.data!,
              borderWidth: widget.borderWidth,
              borderColor: widget.borderColor,
            ),
          );
        }
        return CircularProgressIndicator();
      },
    );
  }
}

class CircleImagePainter extends CustomPainter {
  final ui.Image image;
  final double borderWidth;
  final Color borderColor;

  CircleImagePainter({
    required this.image,
    required this.borderWidth,
    required this.borderColor,
  });

  @override
  void paint(Canvas canvas, Size size) {
    // 创建圆形路径
    final path = Path()
      ..addOval(Rect.fromCircle(
        center: size.center(Offset.zero),
        radius: size.width / 2 - borderWidth,
      ));

    // 应用裁剪
    canvas.clipPath(path);

    // 绘制图片（保持比例居中）
    final srcRect = Rect.fromLTWH(0, 0, image.width.toDouble(), image.height.toDouble());
    final dstRect = Rect.fromLTWH(0, 0, size.width, size.height);
    canvas.drawImageRect(
      image,
      srcRect,
      dstRect,
      Paint()..filterQuality = FilterQuality.high,
    );

    // 绘制边框
    if (borderWidth > 0) {
      final borderPaint = Paint()
        ..color = borderColor
        ..style = PaintingStyle.stroke
        ..strokeWidth = borderWidth
        ..isAntiAlias = true;

      canvas.drawCircle(
        size.center(Offset.zero),
        size.width / 2 - borderWidth / 2,
        borderPaint,
      );
    }
  }

  @override
  bool shouldRepaint(CircleImagePainter oldDelegate) {
    return oldDelegate.image != image ||
        oldDelegate.borderWidth != borderWidth ||
        oldDelegate.borderColor != borderColor;
  }
}
